package com.Webserver.http;

import com.sun.javafx.collections.MappingChange;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 响应对象:
 * 该类的每一个实例用于表示服务端给客户端发送的一个HTTP响应内容，每一个响应有三部分构成:
 * 1.状态行;2.响应头;3.响应正文.
 */
public class HttpResponse {
    /*状态行相关信息*/
    private int statusCode = 200;//默认
    private String statusReason = "OK";

    /*响应头相关信息*/
    private Map<String,String> headers = new HashMap<>();



    /*响应正文相关信息*/
    private File entity;//响应正文对应的实体文件 -> file

    private Socket socket;

    public HttpResponse(Socket socket) {
        this.socket = socket;
    }

    /**
     * 将当前响应对象内容以标准的响应格式发送给客户端.
     */
    public void flush() throws IOException {
        //发送状态行
        sendStatusLine();
        //发送响应头
        sendHeaders();
        //发送响应正文
        sendContent();
    }

    /** 1.发送状态行 */
    private void sendStatusLine() throws IOException {
        String line = "HTTP/1.1" + " " + statusCode + " " + statusReason;
        println(line);
    }

    /** 2.发送响应头 */
    private void sendHeaders() throws IOException {
        /*
        key:                value:
        Content-Typ         text/html   text/css   application/javascript   image/png     image/gif     image/jpeg
        Content-Length      1100
        ......              ...
         */
        Set<Map.Entry<String,String>> entrySet = headers.entrySet();//键值对遍历
        for(Map.Entry<String,String> e : entrySet){
            String name = e.getKey();//响应头的名字
            String value = e.getValue();//响应头对应的值
            String line = name+": "+value;
            println(line);
        }
        //单独发送CRLF表示响应头发送完毕.
        println("");//"":空字符串.->相当于->out.write(13);out.write(10);

    }

    /** 3.发送响应正文 */
    private void sendContent() throws IOException {

        try (/*try(){}单独写原因:1.()会调用finally并close;
                               2.不写catch:不在当期捕获,对外抛出了.*/
                //利用异常处理机制的自动关闭特性,确保文件流使用后被关闭.
                FileInputStream fis = new FileInputStream(entity);
        ) {
            OutputStream out = socket.getOutputStream();
            byte[] data = new byte[1024 * 10];
            int num;//每次实际读取的字节数量.
            while ((num = fis.read(data)) != -1) {
                out.write(data, 0, num);
            }
        }
    }

    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte[] data = line.getBytes("ISO8859-1");
        out.write(data);
        out.write(13);
        out.write(10);
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getEntity() {
        return entity;
    }
    /**
     * 添加响应正文对应的实体文件
     * 添加该文件的同时会根据实体文件自动添加两个说明正文的响应头:Content-Type和Content-Length
     */
    public void setEntity(File entity) {
        this.entity = entity;
        //设置响应头
        //1.根据entity获取该正文的文件名
        //2.根据文件名获取到资源后缀名
        //3.根据资源后缀名设置Content-Type的值
        String len = entity.getName();
        String ext = len.substring(len.lastIndexOf(".")+1);
        String type = HttpContext.getMimeMapping(ext);
        System.out.println(ext+"的mime type:"+type);

        putHeader("Content-Type",type);
        putHeader("Content-Length",entity.length()+"");
    }

    /**
     * 添加一个要发送的响应头
     * @param name
     * @param value
     */
    public void putHeader(String name,String value){
        this.headers.put(name,value);
    }
}
